package leetcode.weekly.week295;

//Solution2Test
public class Solution2 {

	// Solution2Test
	public String discountPrices(String sentence, int discount) {
		String[] words = sentence.split(" ");
		int rest = 100 - discount;
		StringBuffer ans = new StringBuffer();
		for (int i = 0; i < words.length; i++) {
			if (this.isPrice(words[i])) {
				ans.append(this.newPrice(words[i], rest)).append(" ");
			} else {
				ans.append(words[i]).append(" ");
			}
		}
		return ans.substring(0, ans.length() - 1);
	}

	private String newPrice(String string, int rest) {
		long value = Long.valueOf(string.substring(1));
		long newValue = value * rest;
		long a = newValue / 100;
		long b = newValue % 100;

		if (a == 0 && b == 0) {
			return "$0.00";
		}
		if (b == 0) {
			return "$" + a + ".00";
		}
		if (b > 9) {
			return "$" + a + "." + b;
		}
		return "$" + a + ".0" + b;
	}

	private boolean isPrice(String string) {
		if (string.length() < 2) {
			return false;
		}
		if (string.charAt(0) != '$') {
			return false;
		}
		if (!this.isNum(string.charAt(1))) {
			return false;
		}
		int dot = 0;
		for (int i = 2; i < string.length(); i++) {
			char c = string.charAt(i);
			if (c == '.') {
				dot++;
				if (dot > 1) {
					return false;
				}
				continue;
			}
			if (!this.isNum(c)) {
				return false;
			}
		}
		return true;
	}

	private boolean isNum(char c) {
		return c >= '0' && c <= '9';
	}

}
